package com.aiatomic.couting.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

public class HttpUtils {
	public static final int CODE_SUCCESS_RQ_100 = 100;
	public static final int CODE_ERROR_RQ_998 = 998;
	public static final int CODE_ERROR_RQ_999 = 999;
	public static final int RET_SUCCESS = 10000;
	public static final int RET_ERR_ACCOUNT_NON_EXIST = 10002;
	private static HttpUtils _instance;

	private HttpUtils() {
	}

	private static HttpUtils getInstance() {
		if (_instance == null) {
			_instance = new HttpUtils();
		}
		return _instance;
	}

	public static String md5(String string) {
		if (TextUtils.isEmpty(string)) {
			return "";
		}
		MessageDigest md5 = null;
		try {
			md5 = MessageDigest.getInstance("MD5");
			byte[] bytes = md5.digest(string.getBytes());
			String result = "";
			for (byte b : bytes) {
				String temp = Integer.toHexString(b & 0xff);
				if (temp.length() == 1) {
					temp = "0" + temp;
				}
				result += temp;
			}
			return result;
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static void post(final Handler handler, final String path, final Map<String, String> params) {
		HttpUtils.getInstance().request(handler, path, params, "POST");
	}

	public static void get(final Handler handler, final String path, final Map<String, String> params) {
		HttpUtils.getInstance().request(handler, path, params, "GET");
	}

	private void request(final Handler handler, final String path, final Map<String, String> params,
			final String method) {
		Log.i("HTTP_URL", path);
		for (String key : params.keySet()) {
			Log.i("HTTP_PARAMS", key + ": " + params.get(key));
		}
		Thread http = new Thread(new Runnable() {
			@Override
			public void run() {
				StringBuilder response = new StringBuilder();
				StringBuilder body = new StringBuilder();
				for (String key : params.keySet()) {
					String val = params.get(key);
					if(val==null){
						val="null";
					}
					try {
						body.append(key).append("=").append(URLEncoder.encode(val, "UTF-8")).append("&");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
				/*try {
					Thread.sleep(2000);
				} catch (InterruptedException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}*/
				HttpURLConnection connection = null;
				try {
					URL url = new URL(path);
					connection = (HttpURLConnection) url.openConnection();
					connection.setRequestMethod(method);
					connection.setConnectTimeout(5000);
					connection.setReadTimeout(5000);
					connection.setDoOutput(true);
					connection.getOutputStream().write(body.toString().getBytes());
					int code = connection.getResponseCode();
					if (code == HttpURLConnection.HTTP_OK) {
						InputStream in = connection.getInputStream();
						// 下面对获取到的输入流进行读取
						BufferedReader reader = new BufferedReader(new InputStreamReader(in));
						String line;
						while ((line = reader.readLine()) != null) {
							response.append(line);
						}
						Log.i("HTTP_RESPONSE", response.toString());
						Message msg = Message.obtain();
						msg.obj = response.toString();
						msg.what = CODE_SUCCESS_RQ_100;
						handler.sendMessageAtFrontOfQueue(msg);

					} else {
						InputStream in = connection.getErrorStream();
						// 下面对获取到的输入流进行读取
						BufferedReader reader = new BufferedReader(new InputStreamReader(in));
						String line;
						while ((line = reader.readLine()) != null) {
							response.append(line);
						}
						Log.i("HTTP_RESPONSE", response.toString());
						Message msg = Message.obtain();
						msg.obj = response;
						msg.what = CODE_ERROR_RQ_999;
						handler.sendMessageAtFrontOfQueue(msg);
					}
				}catch (SocketException e) {
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.obj = e.getMessage();
					msg.what = CODE_ERROR_RQ_998;
					handler.sendMessageAtFrontOfQueue(msg);
				}catch (SocketTimeoutException e) {
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.obj = e.getMessage();
					msg.what = CODE_ERROR_RQ_998;
					handler.sendMessageAtFrontOfQueue(msg);
				}catch (UnknownHostException e) {
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.obj = e.getMessage();
					msg.what = CODE_ERROR_RQ_998;
					handler.sendMessageAtFrontOfQueue(msg);
				}  catch (Exception e) {
					e.printStackTrace();
					Message msg = Message.obtain();
					msg.obj = e.getMessage();
					msg.what = CODE_ERROR_RQ_999;
					handler.sendMessageAtFrontOfQueue(msg);
				} finally {
					if (connection != null) {
						connection.disconnect();
					}
				}
			}
		});
		http.start();
	}
}
